/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package base.server;

import java.util.Date;

/**
 * This class represents the mean of transmission
 * @author artem, Arvanitis Ioannis
 */
public class Broker implements Runnable {

	private int portOffset;
	private int nodeNumber;
//	private MovementArea movementArea;
//	private ServerSocket[] serverSocket;
//	private Socket[] socket;
	private static ServingThread[] servingThread;
//	public static boolean[] nodeActive;
    

    /**
     * Gets all the serving threads of the broker
     * @return all the serving threads of the broker
     */
    public static ServingThread[] getServingThread() {
        return servingThread;
    }

    /**
     * Gets the indexed serving thread of the broker
     * @param index The index of the serving thread (id-1)
     * @return the indexed serving thread of the broker
     */
    public static ServingThread getServingThread(int index) {
        return servingThread[index];
    }

	/**
	 * Creates an instance of the broker
	 * @param incomingPortOffset The port offset the broker waits for connections. Accordingly, it is the port offset the nodes send their messages
	 * @param outgoingPortOffset The port offset the broker sends messages to the nodes. Accordingly, it is the port offset the nodes listen for new connections
	 * @param nodeNumber The number of nodes participating in the simulation
	 * @param movementArea The movementArea in which the nodes are virtually deployed
	 */
	public Broker(int portOffset, int nodeNumber) {
		print("Initializing the server..");
		this.portOffset = portOffset;
		this.nodeNumber = nodeNumber;
//		this.movementArea = movementArea;
//		nodeActive = new boolean[nodeNumber];
//		serverSocket = new ServerSocket[nodeNumber];
//		socket = new Socket[nodeNumber];
		servingThread = new ServingThread[nodeNumber];
		for (int i=0; i<nodeNumber; i++) {
			servingThread[i] = new ServingThread(portOffset, i+1);
		}
	}

    /**
     * Starts the serving threads
     */
	public void run() {
		for (int i=0; i < nodeNumber; i++) {
			servingThread[i].start();
            print("Serving Thread " + (i+1) + " listening...");
		}
		print("Server initialized");
	}

    /**
     * Interrupts the operations of serving threads
     */
    public void interrupt() {
        for (int i=0; i<nodeNumber; i++) {
            servingThread[i].interrupt();
            print("Serving Thread " + (i+1) + " closing down...");
        }
    }

	/**
	 * Prints a custom message for the server
	 * @param s The string to be printed
	 */
    @SuppressWarnings("static-access")
	public static void print(String s) {
        Date date = new Date();
		System.out.println(" ::BROKER:: " + date.getTime() +"\tServer\t" + s);
	}



//	public static boolean send(Message msg) {
//		return servingThread[msg.getTargetNodes().get(0).getNodeId()].send(msg);
//	}

    
}
